<?php

class Autoconfig extends AppModel {

    var $name = 'Autoconfig';
    var $useTable = false;
    private $autoconfigGenHeader = "/**\n * This file contains automatically generated config variables,\n * so DO NOT MANUALLY CHANGE CONTENT OF THIS FILE!\n *All settings from this file can be configured in admin panel.\n */\n";

    public function save($variables) {
        $configData = Configure::read("Autoconfig");
        foreach ($variables as $var => $value) {
            $configData[$var] = $value;
        }
        
        $out = '<?php ' . $this->autoconfigGenHeader . "\n";
        foreach ($configData as $k => $v) {
            $type = gettype($v);
            $vstr = $v;
            if ($type == "string")
                $vstr = "'" . str_replace("'", "\\'", str_replace("\n", "\\n", str_replace("\r", "\\r", $v))) . "'";
            if ($type == "array")
                $vstr = "unserialize('" . serialize($v) . "')";
            $out .= '$config[\'Autoconfig\'][\'' . $k . '\'] = ' . $vstr . ';';
        }
        $out .= ' ?>';

        $path = CONFIGS . "autoconfig_gen.php";
        $fh = fopen($path, 'w') or die("can't open file");
        if (flock($fh, LOCK_EX)) {
            fwrite($fh, $out);
            flock($fh, LOCK_UN);
        } else {
            trigger_error("AutoConfig is not saved. File locked! Please try to do it later.");
        }
        fclose($fh);
        //debug($configData);
        
        foreach ($variables as $var => $value) {
            Configure::write("Autoconfig.".$var, $value);
        }
    }

}

?>
